// src/containers/InterviewRoom/index.jsx - 修复后的面试房间组件
import { useState, useRef, useEffect } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { 
  Mic, MicOff, Camera, CameraOff, Volume2, VolumeX, 
  Play, Pause, SkipForward, LogOut, Clock
} from 'lucide-react'
import { api, SOCKET_EVENTS } from '../../utils/api'
import './style.css'

const InterviewRoom = () => {
  const { sessionId } = useParams()
  const navigate = useNavigate()
  const videoRef = useRef(null)
  const audioRef = useRef(null)
  
  // 设备状态
  const [stream, setStream] = useState(null)
  const [isMicOn, setIsMicOn] = useState(true)
  const [isCameraOn, setIsCameraOn] = useState(true)
  const [isSpeakerOn, setIsSpeakerOn] = useState(true)
  
  // 面试状态
  const [interviewPhase, setInterviewPhase] = useState('preparing') // preparing, ready, questioning, answering, scoring, completed
  const [currentRound, setCurrentRound] = useState(0)
  const [totalRounds, setTotalRounds] = useState(3)
  const [currentQuestion, setCurrentQuestion] = useState('')
  const [timeRemaining, setTimeRemaining] = useState(60)
  const [isAudioPlaying, setIsAudioPlaying] = useState(false)
  
  // 用户反馈
  const [error, setError] = useState('')
  const [message, setMessage] = useState('')

  // 初始化
  useEffect(() => {
    initializeInterview()
    return cleanup
  }, [sessionId])

  const initializeInterview = async () => {
    try {
      if (!sessionId) {
        navigate('/')
        return
      }

      // 启动摄像头
      await startCamera()
      
      // 连接WebSocket
      setupWebSocket()
      
      setInterviewPhase('ready')
      setMessage('面试环境准备完成，点击开始面试')
      
    } catch (error) {
      console.error('初始化失败:', error)
      setError('面试环境初始化失败')
      setInterviewPhase('error')
    }
  }

  const startCamera = async () => {
    try {
      const mediaStream = await navigator.mediaDevices.getUserMedia({
        video: { width: 640, height: 480 },
        audio: true
      })
      
      setStream(mediaStream)
      
      if (videoRef.current) {
        videoRef.current.srcObject = mediaStream
        videoRef.current.play()
      }
      
      console.log('摄像头启动成功')
    } catch (error) {
      console.error('摄像头启动失败:', error)
      setError('无法访问摄像头，但面试仍可继续')
    }
  }

  const setupWebSocket = () => {
    const socket = api.socket.connect()
    
    // 加入会话
    socket.emit('join_session', { session_id: sessionId })
    
    // 监听事件
    socket.on('joined_session', (data) => {
      console.log('已加入面试会话:', data.session_id)
    })
    
    socket.on('question_start', (data) => {
      console.log('收到新问题:', data)
      setCurrentRound(data.round)
      setTotalRounds(data.total_rounds)
      setCurrentQuestion(data.question)
      setInterviewPhase('questioning')
      setMessage('AI正在提问...')
      
      // 🔥 修复：自动播放问题语音
      playQuestionAudio(data.question)
    })
    
    socket.on('audio_finished', (data) => {
      console.log('音频播放完成:', data)
      setIsAudioPlaying(false)
      if (data.success) {
        setMessage('请开始回答，您有60秒时间')
      } else {
        setMessage('语音播放失败，请看文字题目并开始回答')
      }
    })
    
    socket.on('timer_start', (data) => {
      console.log('开始计时:', data)
      setInterviewPhase('answering')
      setTimeRemaining(data.duration)
      setMessage(`正在录音，剩余时间：${data.duration}秒`)
    })
    
    socket.on('timer_update', (data) => {
      setTimeRemaining(data.remaining)
      setMessage(`正在录音，剩余时间：${data.remaining}秒`)
    })
    
    socket.on('timer_end', (data) => {
      console.log('回答时间结束:', data)
      setInterviewPhase('scoring')
      setMessage('正在处理您的回答...')
    })
    
    // 🔥 新增：处理轮次完成事件
    socket.on('round_completed', (data) => {
      console.log('轮次完成:', data)
      setMessage(`第${data.completed_round}轮已完成，准备下一轮...`)
    })
    
    // 🔥 新增：处理评分更新事件  
    socket.on('score_update', (data) => {
      console.log('收到评分更新:', data)
      // 可以在这里显示评分反馈，但不阻塞面试流程
    })
    
    socket.on('interview_completed', (data) => {
      console.log('面试完成:', data)
      setInterviewPhase('completed')
      setMessage('面试完成！正在生成报告...')
      
      setTimeout(() => {
        navigate(`/result/${sessionId}`)
      }, 3000)
    })
    
    socket.on('error', (data) => {
      console.error('WebSocket错误:', data)
      setError(data.message)
    })
  }

  const startInterview = async () => {
    try {
      setMessage('正在准备面试...')
      
      // 调用后端开始面试
      const response = await api.startInterview(sessionId)
      console.log('面试开始响应:', response)
      
      setMessage('面试即将开始...')
      
      // 开始第一轮
      api.socket.emit('start_first_round', { session_id: sessionId })
      
    } catch (error) {
      console.error('开始面试失败:', error)
      setError(`开始面试失败: ${error.message}`)
    }
  }

  const skipQuestion = () => {
    if (window.confirm('确定要跳过当前问题吗？将立即进入下一轮。')) {
      console.log('⏭️ 用户选择跳过当前问题')
      setMessage('正在进入下一轮...')
      api.socket.emit('skip_question', { session_id: sessionId })
    }
  }

  // 🔥 新增：显示语音识别状态
  const [recognitionStatus, setRecognitionStatus] = useState('')
  const [lastRecognizedText, setLastRecognizedText] = useState('')

  // 🔥 新增：定期获取语音识别状态
  useEffect(() => {
    let statusInterval
    
    if (interviewPhase === 'answering') {
      statusInterval = setInterval(async () => {
        try {
          const response = await api.getRecognitionResult(sessionId)
          if (response && response.current_answer) {
            setLastRecognizedText(response.current_answer)
            setRecognitionStatus('识别到语音')
          } else {
            setRecognitionStatus('等待语音输入...')
          }
        } catch (error) {
          setRecognitionStatus('语音识别服务异常')
        }
      }, 2000) // 每2秒检查一次
    }
    
    return () => {
      if (statusInterval) {
        clearInterval(statusInterval)
      }
    }
  }, [interviewPhase, sessionId])

  const toggleMic = () => {
    if (stream) {
      const audioTrack = stream.getAudioTracks()[0]
      if (audioTrack) {
        audioTrack.enabled = !isMicOn
        setIsMicOn(!isMicOn)
      }
    }
  }

  const toggleCamera = () => {
    if (stream) {
      const videoTrack = stream.getVideoTracks()[0]
      if (videoTrack) {
        videoTrack.enabled = !isCameraOn
        setIsCameraOn(!isCameraOn)
      }
    }
  }

  const toggleSpeaker = () => {
    setIsSpeakerOn(!isSpeakerOn)
    if (audioRef.current) {
      audioRef.current.muted = isSpeakerOn
    }
  }

  // 🔥 新增：播放问题语音
  const playQuestionAudio = async (questionText) => {
    try {
      console.log('🔊 开始播放问题语音:', questionText.substring(0, 50))
      setIsAudioPlaying(true)
      
      // 调用TTS API
      const audioResponse = await api.synthesizeSpeech(questionText)
      
      if (audioResponse instanceof Blob && audioResponse.size > 0) {
        console.log('✅ 收到音频数据，开始播放')
        
        // 播放音频
        if (audioRef.current) {
          const audioUrl = URL.createObjectURL(audioResponse)
          
          audioRef.current.onended = () => {
            console.log('🔊 音频播放完成')
            setIsAudioPlaying(false)
            URL.revokeObjectURL(audioUrl)
            
            // 开始回答阶段
            setInterviewPhase('answering')
            setMessage('请开始回答，您有60秒时间')
          }
          
          audioRef.current.onerror = (e) => {
            console.error('❌ 音频播放错误:', e)
            setIsAudioPlaying(false)
            URL.revokeObjectURL(audioUrl)
            
            // 即使音频失败也继续面试
            setInterviewPhase('answering')
            setMessage('语音播放失败，请看文字题目并开始回答')
          }
          
          audioRef.current.src = audioUrl
          audioRef.current.volume = isSpeakerOn ? 1.0 : 0.0
          
          try {
            await audioRef.current.play()
            console.log('▶️ 音频开始播放')
          } catch (playError) {
            console.error('❌ 音频播放失败:', playError)
            setIsAudioPlaying(false)
            setInterviewPhase('answering')
            setMessage('语音播放失败，请看文字题目并开始回答')
          }
        }
      } else {
        console.warn('⚠️ 语音合成失败，使用文字模式')
        setIsAudioPlaying(false)
        setInterviewPhase('answering')  
        setMessage('语音合成失败，请看文字题目并开始回答')
      }
      
    } catch (error) {
      console.error('❌ 播放问题语音失败:', error)
      setIsAudioPlaying(false)
      setInterviewPhase('answering')
      setMessage('语音播放失败，请看文字题目并开始回答')
    }
  }

  // 🔥 新增：摄像头测试功能
  const testCamera = async () => {
    try {
      console.log('🧪 测试摄像头功能...')
      
      // 获取设备列表
      const devices = await navigator.mediaDevices.enumerateDevices()
      const videoDevices = devices.filter(device => device.kind === 'videoinput')
      
      console.log('📹 可用摄像头设备:', videoDevices.length)
      videoDevices.forEach((device, index) => {
        console.log(`设备${index + 1}:`, device.label || `摄像头${index + 1}`)
      })
      
      if (videoDevices.length === 0) {
        throw new Error('未找到摄像头设备')
      }
      
      // 测试获取视频流
      const testStream = await navigator.mediaDevices.getUserMedia({
        video: { deviceId: videoDevices[0].deviceId }
      })
      
      console.log('✅ 摄像头测试成功')
      
      // 如果videoRef存在，直接设置流
      if (videoRef.current) {
        videoRef.current.srcObject = testStream
        setStream(testStream)
        setIsCameraOn(true)
        setMessage('摄像头测试成功，视频已显示')
      }
      
      return true
      
    } catch (error) {
      console.error('❌ 摄像头测试失败:', error)
      setError(`摄像头测试失败: ${error.message}`)
      return false
    }
  }

  const exitInterview = () => {
    if (window.confirm('确定要退出面试吗？')) {
      cleanup()
      navigate('/')
    }
  }

  const cleanup = () => {
    if (stream) {
      stream.getTracks().forEach(track => track.stop())
    }
    api.socket.disconnect()
  }

  const formatTime = (seconds) => {
    const mins = Math.floor(seconds / 60)
    const secs = seconds % 60
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }

  const getPhaseText = () => {
    switch (interviewPhase) {
      case 'preparing': return '准备中...'
      case 'ready': return '准备完成'
      case 'questioning': return 'AI提问中'
      case 'answering': return '回答中'
      case 'scoring': return '评分中'
      case 'completed': return '面试完成'
      default: return ''
    }
  }

  const getPhaseColor = () => {
    switch (interviewPhase) {
      case 'ready': return '#28a745'
      case 'questioning': return '#007bff'
      case 'answering': return '#fd7e14'
      case 'scoring': return '#6f42c1'
      case 'completed': return '#28a745'
      default: return '#6c757d'
    }
  }

  // 错误状态
  if (interviewPhase === 'error') {
    return (
      <div className="room-interview-room room-error">
        <div className="room-error-container">
          <h2>面试启动失败</h2>
          <p>{error}</p>
          <button onClick={() => navigate('/')} className="room-back-btn">
            返回首页
          </button>
        </div>
      </div>
    )
  }

  return (
    <div className="room-interview-room">
      {/* 顶部状态栏 */}
      <div className="room-header">
        <div className="room-interview-status">
          <div className="room-phase-indicator" style={{ color: getPhaseColor() }}>
            <span className="room-phase-text">{getPhaseText()}</span>
          </div>
          
          {currentRound > 0 && (
            <div className="room-round-indicator">
              第 {currentRound} / {totalRounds} 轮
            </div>
          )}
          
          {interviewPhase === 'answering' && (
            <div className="room-timer-display">
              <Clock size={16} />
              <span className="room-time">{formatTime(timeRemaining)}</span>
            </div>
          )}
        </div>
        
        <div className="room-controls">
          <button 
            className="room-control-btn room-exit-btn" 
            onClick={exitInterview}
            title="退出面试"
          >
            <LogOut size={20} />
          </button>
        </div>
      </div>

      {/* 错误提示 */}
      {error && (
        <div className="room-alert room-alert-error">
          {error}
          <button onClick={() => setError('')}>×</button>
        </div>
      )}

      {/* 主内容区 */}
      <div className="room-main-content">
        {/* AI面试官区域 */}
        <div className="room-ai-section">
          <div className="room-ai-avatar">
            <div className="room-avatar">
              👨‍💼
              {isAudioPlaying && (
                <div className="room-speaking-animation">
                  <div className="room-wave"></div>
                  <div className="room-wave"></div>
                  <div className="room-wave"></div>
                </div>
              )}
            </div>
            <div className="room-ai-info">
              <h3>AI面试官</h3>
              <p>专业面试评估</p>
            </div>
          </div>
          
          {/* 问题显示区 */}
          <div className="room-question-area">
            <div className="room-question-header">
              <h4>面试问题</h4>
              {interviewPhase === 'answering' && (
                <button 
                  className="room-skip-btn"
                  onClick={skipQuestion}
                  title="跳过当前问题"
                >
                  <SkipForward size={16} />
                  跳过
                </button>
              )}
            </div>
            
            <div className="room-question-content">
              {currentQuestion ? (
                <p className="room-question-text">{currentQuestion}</p>
              ) : (
                <p className="room-placeholder">等待面试开始...</p>
              )}
            </div>
            
            {/* 状态消息 */}
            <div className="room-status-message">
              <p>{message}</p>
            </div>
          </div>
        </div>

        {/* 用户视频区域 */}
        <div className="room-user-section">
          <div className="room-user-video-container">
            {/* 🔥 调试信息 */}
            {process.env.NODE_ENV === 'development' && (
              <div className="room-debug-info">
                <small>摄像头状态: {isCameraOn ? '✅开启' : '❌关闭'}</small>
                <small>视频流: {stream ? '✅已获取' : '❌未获取'}</small>
              </div>
            )}
            
            <video
              ref={videoRef}
              autoPlay
              playsInline
              muted
              className={`room-user-video ${!isCameraOn ? 'room-camera-off' : ''}`}
              style={{
                width: '100%',
                height: '100%',
                objectFit: 'cover',
                backgroundColor: '#000',
                display: 'block'  // 确保显示
              }}
            />
            
            {!isCameraOn && (
              <div className="room-camera-off-overlay">
                <CameraOff size={48} />
                <span>摄像头已关闭</span>
                <button 
                  onClick={startCamera}
                  className="room-retry-camera-btn"
                >
                  重新启动摄像头
                </button>
              </div>
            )}
            <div className="room-user-label">您</div>
          </div>
          
          {/* 录音状态指示 */}
          {interviewPhase === 'answering' && (
            <div className="room-recording-indicator">
              <div className="room-recording-icon"></div>
              <div className="room-recording-status">
                <div>正在录音...</div>
                <div className="room-recognition-status">
                  <small>🎤 {recognitionStatus}</small>
                </div>
                {lastRecognizedText && (
                  <div className="room-recognized-text">
                    <small>📝 识别到: {lastRecognizedText.length > 50 ? 
                      lastRecognizedText.substring(0, 50) + '...' : 
                      lastRecognizedText}
                    </small>
                  </div>
                )}
              </div>
            </div>
          )}
        </div>
      </div>

      {/* 底部控制栏 */}
      <div className="room-bottom-controls">
        {/* 媒体控制 */}
        <div className="room-media-controls">
          <button 
            className={`room-control-btn ${!isMicOn ? 'room-disabled' : ''}`}
            onClick={toggleMic}
            title={isMicOn ? '关闭麦克风' : '开启麦克风'}
          >
            {isMicOn ? <Mic size={20} /> : <MicOff size={20} />}
          </button>
          
          <button 
            className={`room-control-btn ${!isCameraOn ? 'room-disabled' : ''}`}
            onClick={toggleCamera}
            title={isCameraOn ? '关闭摄像头' : '开启摄像头'}
          >
            {isCameraOn ? <Camera size={20} /> : <CameraOff size={20} />}
          </button>
          
          <button 
            className={`room-control-btn ${!isSpeakerOn ? 'room-disabled' : ''}`}
            onClick={toggleSpeaker}
            title={isSpeakerOn ? '关闭扬声器' : '开启扬声器'}
          >
            {isSpeakerOn ? <Volume2 size={20} /> : <VolumeX size={20} />}
          </button>
        </div>

        {/* 面试控制 */}
        <div className="room-interview-controls">
          {interviewPhase === 'ready' && (
            <button 
              className="room-start-interview-btn"
              onClick={startInterview}
            >
              <Play size={20} />
              开始面试
            </button>
          )}
          
          {interviewPhase === 'completed' && (
            <div className="room-completion-message">
              <span>🎉 面试完成！正在跳转到结果页...</span>
            </div>
          )}
        </div>

        {/* 进度条 */}
        {currentRound > 0 && (
          <div className="room-progress-section">
            <div className="room-progress-bar">
              <div 
                className="room-progress-fill"
                style={{ width: `${(currentRound / totalRounds) * 100}%` }}
              ></div>
            </div>
            <span className="room-progress-text">
              进度: {currentRound}/{totalRounds}
            </span>
          </div>
        )}
      </div>

      {/* 隐藏音频元素 */}
      <audio 
        ref={audioRef}
        style={{ display: 'none' }}
        controls={false}
      />
    </div>
  )
}

export default InterviewRoom